package org.goyo.main.web.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.goyo.common.excel.ExcelUtil;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.system.IBillNumberService;
import org.goyo.main.services.system.ISystemService;
import org.goyo.main.web.controller.system.SessionUtil;

public abstract class BaseController {
	
	@Resource
	private ISystemService systemService;
	@Resource
	private IBillNumberService billNumberService;
	/**
	 * 当前用户
	 * 
	 * @author chenchuan
	 * 2014年11月21日
	 */
	public SysUser getCurrentUser(){
		SysUser user = null;
		user = (SysUser)SessionUtil.getAttribute("user");
		return user;
	}
	
	/**
	 * 通过用户获得组织部门
	 * 
	 * @author chenchuan
	 * 2014年11月23日
	 */
	public List<SysDepGroup> getUserDepGroup(SysUser user){
		Map<String,List<SysDepGroup>> map = systemService.getAllDepGroup();
		List<SysDepGroup> groupList = map.get(user.getUuid());
		return groupList;
	}
	
	/**
	 * 获取单据编号
	 * @param biztype
	 * @return
	 */
	public String getBillNumber(String biztype){
		return billNumberService.getBillNumber(biztype);
	}
	
	public String getBaseNumber(String biztype){
		return billNumberService.getBaseNumber(biztype);
	}
	
	protected void downfile(HttpServletResponse response, File file,
			String filename) {
		try {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);

			// 设置编码
			response.setCharacterEncoding("ISO-8859-1");
			//response.setCharacterEncoding("utf-8");
			// response.setContentType("text/html; charset=ISO-8859-1");
			response.reset();
			// 设置response的编码方式
			String contentType = getContentType(filename);
			response.setContentType(contentType);
			// response.setContentType("multipart/byteranges");
			// 写明要下载的文件的大小
			response.setContentLength((int) file.length());
			// 发送到客户端的文章
			filename = new String(filename.getBytes(),"ISO-8859-1");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ filename);
			// 读出文件到i/o流
			FileInputStream fis = new FileInputStream(file);

			BufferedInputStream buff = new BufferedInputStream(fis);

			byte[] b = new byte[2048];// 相当于我们的缓存

			long k = 0;// 该值用于计算当前实际下载了多少字节
			// 从response对象中得到输出流,准备下载
			response.setBufferSize(2048);
			OutputStream myout = response.getOutputStream();
			// 开始循环下载
			while (k < file.length()) {
				int j = buff.read(b, 0, 2048);
				k += j;
				// 将b中的数据写到客户端的内存
				myout.write(b, 0, j);
			}
			myout.flush();
			fis.close();
			buff.close();
			myout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param filename
	 * @return
	 */
	private String getContentType(String filename) {
		if (filename == null) {
			return null;
		}

		if (filename.lastIndexOf(".") == -1) {
			return "application/x-msdownload";
		}
		String extension = filename.substring(filename.lastIndexOf(".") + 1);
		extension = extension.toLowerCase();
		if ("mp3".equals(extension)) {
			return "audio/x-mpeg";
		} else if ("mid".equals(extension)) {
			return "audio/x-midi";
		} else if ("midi".equals(extension)) {
			return "audio/x-midi";
		} else if ("mpa".equals(extension)) {
			return "audio/x-mpeg";
		} else if ("abs".equals(extension)) {
			return "audio/x-mpeg";
		} else if ("aif".equals(extension)) {
			return "audio/x-aiff";
		} else if ("wav".equals(extension)) {
			return "audio/x-wav";
		} else if ("swf".equals(extension)) {
			return "application/x-shockwave-flash";
		} else if ("doc".equals(extension)) {
			return "application/msword";
		} else if ("avi".equals(extension)) {
			return "video/x-msvideo";
		} else if ("au".equals(extension)) {
			return "audio/basic";
		} else if ("exe".equals(extension)) {
			return "application/octet-stream";
		} else if ("pdf".equals(extension)) {
			return "application/pdf";
		} else if ("txt".equals(extension)) {
			return "text/plain";
		} else if ("zip".equals(extension)) {
			return "application/zip";
		}
		return "application/x-msdownload";
	}
	
	
	/**
     * 导出excel
     * @param data
     * @param form
     * @param filename
     * @param class1
     * @param response 
     */
    protected void execlExport(List data, String form, String filename, HttpServletResponse response){
        OutputStream ouputStream = null;
        ByteArrayOutputStream os = null;
        try {
            Workbook wb = ExcelUtil.ExcelExport(form, data);
            if(null!=wb){/*
              
              
              
                os = new ByteArrayOutputStream();  
                wb.write(os);  
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                filename = new String(filename.getBytes(), "UTF-8");
                filename = System.currentTimeMillis() + "."+form;
                response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
                
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
                // 设置编码
                response.setCharacterEncoding("ISO-8859-1");
                response.reset();
//              // 写明要下载的文件的大小
              //  response.setContentLength(os.toByteArray().length);
                // 发送到客户端的文章
                //filename = new String(filename.getBytes(), "UTF-8");
//              response.setHeader("Content-Disposition", "attachment;filename="
//                      + filename);
               // response.setBufferSize(2048);
                response.setContentType("application/vnd.ms-excel"); 
               // response.setContentType("application/x-msexcel");
               // response.setHeader("Content-Disposition", "attachment;filename="+filename+"."+form);  
                ouputStream = response.getOutputStream();  
                wb.write(ouputStream);  
                //ouputStream.flush(); 
                ouputStream.close();
            */
              response.setHeader("Pragma", "no-cache");
              response.setHeader("Cache-Control", "no-cache");
              response.setDateHeader("Expires", 0);
              // 设置编码
              response.setCharacterEncoding("ISO-8859-1");
              response.reset();
//            // 写明要下载的文件的大小
              // 发送到客户端的文章
              filename = new String(filename.getBytes(), "ISO-8859-1");
//            response.setHeader("Content-Disposition", "attachment;filename="
//                    + filename);
              response.setContentType("application/vnd.ms-excel");  
              response.setHeader("Content-disposition", "attachment;filename="+filename+"."+form);  
              ouputStream = response.getOutputStream();  
              wb.write(ouputStream);  
              ouputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null!=ouputStream){
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
            
    }
    
    
    /**
     * 导出自定义数据excel
     * @param data
     * @param form
     * @param filename
     * @param class1
     * @param response 
     */
    protected void UserDefinedExeclExport(List<Object[]> data,List<String> titles, String form, String filename, HttpServletResponse response){
        OutputStream ouputStream = null;
        ByteArrayOutputStream os = null;
        try {
            Workbook wb = ExcelUtil.UserDefinedExcelExport(form, titles, data);
            if(null!=wb){
                os = new ByteArrayOutputStream();  
                wb.write(os);  
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
                // 设置编码
                response.setCharacterEncoding("UTF-8");
                response.reset();
//              // 写明要下载的文件的大小
                response.setContentLength(os.toByteArray().length);
                // 发送到客户端的文章
                filename = new String(filename.getBytes(), "UTF-8");
//              response.setHeader("Content-Disposition", "attachment;filename="
//                      + filename);
                response.setBufferSize(2048);
                response.setContentType("application/vnd.ms-excel");  
                response.setHeader("Content-disposition", "attachment;filename="+filename+"."+form);  
                ouputStream = response.getOutputStream();  
                wb.write(ouputStream);  
                ouputStream.flush();  
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null!=ouputStream){
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
            
    }
    
    /**
     * 导出excel
     * @param data
     * @param form
     * @param filename
     * @param class1
     * @param response 
     */
    protected void execlExport(Workbook wb, String filename, HttpServletResponse response){
        OutputStream ouputStream = null;
        ByteArrayOutputStream os = null;
        try {
            if(null!=wb){
                os = new ByteArrayOutputStream();  
                wb.write(os);  
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
                // 设置编码
                response.setCharacterEncoding("ISO-8859-1");
                response.reset();
//              // 写明要下载的文件的大小
                response.setContentLength(os.toByteArray().length);
                // 发送到客户端的文章
                filename = new String(filename.getBytes(), "ISO-8859-1");
//              response.setHeader("Content-Disposition", "attachment;filename="
//                      + filename);
                response.setBufferSize(2048);
                response.setContentType("application/vnd.ms-excel");  
                response.setHeader("Content-disposition", "attachment;filename="+filename+".xls");  
                ouputStream = response.getOutputStream();  
                wb.write(ouputStream);  
                ouputStream.flush();  
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null!=ouputStream){
                try {
                    ouputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
            
    }


	
}
